package org.example.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author zjj
 * @date 2019/6/11 0011
 * @describe 浏览器跨域问题
 */
@WebFilter(urlPatterns = "/*", filterName = "crossDomainFilter")
@Order(1)
public class CrossDomainFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CrossDomainFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("CrossDomainFilter execute init() method ... ");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse)servletResponse;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers","Content-Type");
        response.setHeader("Access-Control-Max-Age","1800");

        filterChain.doFilter(servletRequest, response);
    }


    @Override
    public void destroy() {
        logger.info("CrossDomainFilter execute destroy() method ... ");
    }


}
